//app.js
App({
  onLaunch:function(){
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
  },
   //获取用户信息
  getUserInfo:function(cb){
    var that = this
    if(this.globalData.userInfo){
      typeof cb == "function" && cb(this.globalData.userInfo)
    }else{
      wx.getUserInfo({
        withCredentials:false,
        success:function(res){
          that.globalData.userInfo = res.userInfo
          typeof cb == "function" && cb(that.globalData.userInfo)
        }
      })
    }
  },
  //获取openid
  getOpenid: function (cb) {
    var that = this
    if (this.globalData.openid) {
      typeof cb == "function" && cb(that.globalData.userInfo)
    } else {
      //调用微信登录接口  
      wx.login({
        success: function (loginCode) {
          var appid = 'wx7d5832004cdcf48e'; //填写微信小程序appid  
          var secret = '20437f4dee55679880a94362e4c2ac78'; //填写微信小程序secret  

          //调用request请求api转换登录凭证  
          wx.request({
            url: 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid + '&secret=' + secret + '&grant_type=authorization_code&js_code=' + loginCode.code,
            header: {
              'content-type': 'application/json'
            },
            success: function (res) {
              //console.log(res.data.openid) //获取openid  
              that.globalData.openid = res.data.openid
              typeof cb == "function" && cb(that.globalData.openid)
            }
          })
        }
      })
    }
  },
  globalData:{
    webroot:'localhost',
    userInfo:null,
    openid:null
  }
})